package com.example.wisdomclassroomapi.facade.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wisdomclassroomapi.application.service.CourseLessonApplicationService;
import com.example.wisdomclassroomapi.application.service.GradeLessonBindApplicationService;
import com.example.wisdomclassroomapi.common.dto.PageDto;
import com.example.wisdomclassroomapi.common.util.IdentificationUtil;
import com.example.wisdomclassroomapi.domain.entity.CourseLessonEntity;
import com.example.wisdomclassroomapi.domain.entity.GradeLessonBindEntity;
import com.example.wisdomclassroomapi.domain.entity.GradeMajorSubjectBindEntity;
import com.example.wisdomclassroomapi.facade.assembler.CourseLessonFacadeAssembler;
import com.example.wisdomclassroomapi.facade.controller.common.BaseController;
import com.example.wisdomclassroomapi.facade.dto.CourseLessonRequestDto;
import com.example.wisdomclassroomapi.facade.dto.CourseLessonResponseDto;
import com.example.wisdomclassroomapi.facade.dto.SearcherLessonRequestDto;
import com.example.wisdomclassroomapi.infrastructure.mapper.CourseLessonMapper;
import com.example.wisdomclassroomapi.infrastructure.mapper.GradeMajorSubjectBindMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.example.wisdomclassroomapi.facade.controller.wxapp
 * @Description: <前端控制器>-相关接口
 * @Author: scholes
 * @CreateDate: 2022-04-18
 * @UpdateUser: scholes
 * @UpdateDate: 2022-04-18
 * @UpdateRemark: <>
 * @Version: 1.0
 */
@RestController
@RequestMapping("/api/courseLesson")
@Slf4j
public class CourseLessonController extends BaseController {
    @Resource
    private CourseLessonApplicationService courseLessonApplicationService;

    @Resource
    private CourseLessonMapper lessonMapper;

    @Resource
    private GradeMajorSubjectBindMapper gradeMajorSubjectBindMapper;

    @Resource
    private GradeLessonBindApplicationService gradeLessonBindApplicationService;

    @Resource
    private CourseLessonFacadeAssembler courseLessonFacadeAssembler;

    /**
     * 分页查询
     */
    @PostMapping("/page")
    public PageDto<List<CourseLessonResponseDto>> getCourseLessonByPage(@RequestBody @Valid CourseLessonRequestDto request) {
        IPage<CourseLessonEntity> page = new Page<CourseLessonEntity>();
        page.setSize(request.getPageSize());
        page.setCurrent(request.getPageNum());
        CourseLessonEntity entity = courseLessonFacadeAssembler.assembleCourseLessonEntity(request);
        page = courseLessonApplicationService.page(entity, page);
        List<CourseLessonResponseDto> assembleData = new ArrayList<>();
        if (page != null && page.getRecords() != null && page.getRecords().size() > 0) {
            for (CourseLessonEntity item : page.getRecords()) {
                assembleData.add(courseLessonFacadeAssembler.assembleCourseLessonResponseDto(item));
            }
        }
        PageDto<List<CourseLessonResponseDto>> result = new PageDto<>();
        result.setPageSize((int) page.getSize());
        result.setPageNum((int) page.getCurrent());
        result.setTotal(page.getTotal());
        result.setData(assembleData);
        return result;
    }


    /**
     * 查询
     */
    @PostMapping("/list")
    public List<CourseLessonResponseDto> getCourseLessons(@RequestBody @Valid CourseLessonRequestDto request) {
        CourseLessonEntity entity = courseLessonFacadeAssembler.assembleCourseLessonEntity(request);
        List<CourseLessonEntity> list = courseLessonApplicationService.list(entity);
        List<CourseLessonResponseDto> assembleData = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (CourseLessonEntity item : list) {
                assembleData.add(courseLessonFacadeAssembler.assembleCourseLessonResponseDto(item));
            }
        }
        return assembleData;
    }

    /**
     * 获取某一实体
     */
    @PostMapping("/getById")
    public CourseLessonResponseDto getCourseLessonDetails(@RequestBody Map<String, String> params) {
        CourseLessonEntity entity = courseLessonApplicationService.findById(params.get("id"));
        CourseLessonResponseDto responseDto = null;
        if (entity != null) {
            responseDto = courseLessonFacadeAssembler.assembleCourseLessonResponseDto(entity);
        }
        return responseDto;
    }

    /**
     * 新增数据
     */
    @PostMapping("/add")
    public List<String> saveCourseLesson(@RequestBody CourseLessonRequestDto request) {
        CourseLessonEntity entity = courseLessonFacadeAssembler.assembleCourseLessonEntity(request);
//       courseLessonApplicationService.add(entity);

        lessonMapper.insert(entity);

        List<String> result = new ArrayList<>();
        result.add(entity.getId());
        return result;
    }

    /**
     * 修改数据
     */
    @PostMapping("/update")
    public void modifyCourseLesson(@RequestBody CourseLessonEntity request) {
        courseLessonApplicationService.updateById(request);
    }

    /**
     * 删除数据
     */
    @PostMapping("/delete")
    public void removeCourseLesson(@RequestBody @Valid String id) {
        courseLessonApplicationService.deleteById(id);
    }


    @PostMapping("/cover/upload")
    public Boolean uploadCover(@RequestParam MultipartFile file, @RequestParam String lessonId) throws IOException {

        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = "D:\\Develop\\SoundCode\\BS-Project\\wisdom-classroom-image\\img\\userImg\\";
        fileName = IdentificationUtil.shortUuid() + suffixName;

        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);

        String url = "http://localhost:8011/img/userImg/" + fileName;

        CourseLessonEntity courseLessonEntity = new CourseLessonEntity();
        courseLessonEntity.setId(lessonId);
        courseLessonEntity.setCoverUrl(url);

        courseLessonApplicationService.updateById(courseLessonEntity);

        return true;
    }

    @PostMapping("/bind/list")
    public List<CourseLessonEntity> getBindLesson(@RequestBody Map<String, String> params) {
        GradeLessonBindEntity gradeLessonBindEntity= new GradeLessonBindEntity();
        gradeLessonBindEntity.setGradeId(params.get("gradeId"));
        CourseLessonEntity courseLessonEntity = new CourseLessonEntity();
        courseLessonEntity.setTeacherId(params.get("teacherId"));

        List<GradeLessonBindEntity> list = gradeLessonBindApplicationService.list(gradeLessonBindEntity);
        List<CourseLessonEntity> list1 = courseLessonApplicationService.list(courseLessonEntity);

        List<CourseLessonEntity> result = new ArrayList<>();

        for (GradeLessonBindEntity entity: list) {
            for (CourseLessonEntity entity1: list1) {
                if (entity.getLessonId().equals(entity1.getId())) result.add(entity1);
            }
        }

        return result;
    }

    @PostMapping("/searcher")
    public IPage<CourseLessonEntity> getPageSearcher(@RequestBody SearcherLessonRequestDto dto) {
        List<String> subjectIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(dto.getMajorId())) {
            QueryWrapper<GradeMajorSubjectBindEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("major_id", dto.getMajorId());
            gradeMajorSubjectBindMapper.selectList(wrapper).forEach(a -> {
                subjectIds.add(a.getSubjectId());
           });
        }

        IPage<CourseLessonEntity> page = new Page<>();
        page.setCurrent(dto.getPageNum());
        page.setSize(dto.getPageSize());
        QueryWrapper<CourseLessonEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getMajorId()) && subjectIds.isEmpty()) {
            return page;
        }
        if (!subjectIds.isEmpty()) {
            wrapper.in("subject_id", subjectIds);
        }
        if (StringUtils.isNotEmpty(dto.getSubjectType())) {
            wrapper.eq("type", dto.getSubjectType());
        }
        page = lessonMapper.selectPage(page, wrapper);

        return page;
    }

}